<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Db;
use think\Model;
class Mrps extends Model
{

    // 表名
    protected $name = 'kuyou_mrp';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->field('id,purchase_code,purchase_time,delivery_time,workshop_id,number,all_money,examine_id,examine_time,preparation_id,examine_id,operation_id,mrp_status,createtime')->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->field('id,purchase_code,purchase_time,delivery_time,workshop_id,number,all_money,examine_id,examine_time,preparation_id,examine_id,operation_id,mrp_status,createtime')->select())->toArray();
        }
        $adminList = (new Commons())->adminList();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['purchase_time'] = date('Y-m-d',$list_v['purchase_time']);
            $list[$list_k]['delivery_time'] = date('Y-m-d',$list_v['delivery_time']);
            $list[$list_k]['preparation_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['preparation_id']]:'';
            $list[$list_k]['operation_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['operation_id']]:'';
            $list[$list_k]['createtime'] = date('Y-m-d H:i:s',$list_v['createtime']);
            $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->value('name');
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号' =>'require',
                'info_id|单据详情'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $number_decimal= (new Commons())->getSet('number_decimal','value');
                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$detail['purchase_code']])->find();

                $info = Db::name('kuyou_plan_info')->where(['id'=>['in',$detail['info_id']]])->select();
                $data = [];
                foreach ($info as $info_k=>$info_v){
                    $bom = Db::name('kuyou_bom')->where(['goods_code'=>$info_v['goods_code']])->column('id');
                    $info_id = Db::name('kuyou_bom_info')->where(['bom_id'=>['in',$bom]])->select();
                    foreach ($info_id as $info_id_k=>$info_id_v){
                        $info_id_v['number'] = $info_id_v['number']*$info_v['number'];
                        $info_id_v['basic_nmber'] = $info_id_v['basic_nmber']*$info_v['number'];
                        $info_id_v['money'] = $info_id_v['money']*$info_v['number'];
                        $stock = Db::name('kuyou_goods_stock')->where(['goods_code'=>$info_id_v['goods_code']])->sum('stock');
                        $buy_number = 0;
                        if($stock<$info_id_v['basic_nmber'] && $info_id_v['number']==$info_id_v['basic_nmber']){
                            $buy_number = round($info_id_v['number']-$stock,$number_decimal);
                        }else if($stock<$info_id_v['basic_nmber'] && $info_id_v['number']!=$info_id_v['basic_nmber']){
                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$info_id_v['goods_code']])
                                ->field('goods_type_id,goods_code,goods_name,goods_specification_id,note,unit_id,more_unit,goods_barcode')
                                ->find();;
                            $unit = Db::name('kuyou_unit')->where(['id'=>$goods['unit_id']])->field('id,name')->find();
                            $advance_rate = Db::name('kuyou_unit_conversion')->alias('uc')
                                ->join('kuyou_unit u','u.id=uc.vice_unit')
                                ->where(['uc.main_unit'=>$unit['id'],'id'=>$info_id_v['unit_id']])
                                ->value('advance_rate');
                            if($advance_rate){
                                $stock = round($stock/$advance_rate,$number_decimal);
                                $buy_number = round($info_id_v['number']-$stock,$number_decimal);
                            }
                        }
                        $data[] = [
                            'goods_id' => $info_id_v['goods_id'],
                            'goods_code' => $info_id_v['goods_code'],
                            'goods_name' => $info_id_v['goods_name'],
                            'goods_note' => $info_id_v['goods_note'],
                            'unit_id' => $info_id_v['unit_id'],
                            'default_unit' => $info_id_v['default_unit'],
                            'purchase' => $info_id_v['purchase'],
                            'number' => $info_id_v['number'],
                            'basic_nmber' => $info_id_v['basic_nmber'],
                            'stock' => $stock,
                            'buy_number' => $buy_number,
                            'money' => $info_id_v['money'],
                            'remark' => $info_id_v['remark'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }

                if($plan){
                    unset($plan['id']);
                    $plan['createtime'] = time();
                    $plan['updatetime'] = time();
                }else {
                    return ['status'=>500,'msg'=>'未找到生产计划'];
                }

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($plan)){
                        $result = (new Mrps())->insertGetId($plan);
                        foreach ($data as $data_k=>$data_v){
                            $data[$data_k]['plan_id'] = $result;
                        }
                        Db::name('kuyou_mrp_info')->insertAll($data);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $result = false;$msg = $e->getMessage();
                }
                if($result){
                    return ['status'=>200,'msg'=>$result];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'添加失败')];
                }
            }
        }
    }

    /**
     * 原料清单
     * @param array $detail
     * @return array
     */
    public static function editDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $info = Db::name('kuyou_mrp_info')->where(['plan_id'=>$id])->select();
            foreach ($info as $info_k=>$info_v){
                $info[$info_k]['unit'] = Db::name('kuyou_unit')->where(['id'=>$info_v['unit_id']])->find();
            }
            return ['status'=>200,'msg'=>'查询成功','data'=>$info];
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $list = (new Mrps())->where(['id'=>['in',$id]])->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $exa['status']=1;
                    if(isset($exa['status']) && $exa['status']==1){
                        $count += $v->delete();
                        Db::name('kuyou_mrp_info')->where(['plan_id'=>$v['id']])->delete();
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $count = 0;
            }
            if($count){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }
}
